package liquidfs.ui.ftp;

import liquidfs.*;

import java.io.*;
import java.util.*;
import java.util.logging.*;

import org.apache.ftpserver.*;
import org.apache.ftpserver.ftplet.*;
import org.apache.ftpserver.listener.*;
import org.apache.ftpserver.usermanager.*;
import org.apache.ftpserver.usermanager.impl.*;

public class FtpServerInterface implements Runnable {

   private Application app;
   private LiquidFileSystemFactory fsf;
   
   private static Logger log = Logger.getLogger("liquidfs.ui.ftp");
   
   public FtpServerInterface (Application app) {
      this.app = app;
      this.fsf = new LiquidFileSystemFactory(app);
   }
   
   public void run () {
      
      FtpServerFactory serverFactory = new FtpServerFactory();
      
      PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
      //userManagerFactory.setFile(new File("myusers.properties"));
      userManagerFactory.setPasswordEncryptor(
         new PasswordEncryptor()
         {

            @Override
            public String encrypt(String pass) {
               return pass;
            }

            @Override
            public boolean matches(String user, String pass) {
               return true;
            }
         }
      );
      UserManager userManager = userManagerFactory.createUserManager();
      
      BaseUser user = new BaseUser();
      user.setName("test");
      user.setPassword("test");
      user.setHomeDirectory("/");
      
      List<Authority> auths = new ArrayList<Authority>();
      Authority auth = new WritePermission();
      auths.add(auth);
      user.setAuthorities(auths);
      
      try {
          userManager.save(user);
      } catch (FtpException e1) {
          // TODO Auto-generated catch block
          e1.printStackTrace();
      }
      
      ListenerFactory factory = new ListenerFactory();
      
      // set the file system abstraction
      serverFactory.setFileSystem(fsf);
      serverFactory.setUserManager(userManager);
      
      // set the port of the listener
      factory.setPort(this.app.getConfiguration().getFtpPort());
      
      // replace the default listener
      Listener listener = factory.createListener();
      serverFactory.addListener("default", listener);
      
      // start the server
      FtpServer server = serverFactory.createServer();       
      
      // start the server
      try {
         log.info("Starting FTP Server on port" + this.app.getConfiguration().getFtpPort());
         server.start();
      } 
      catch (FtpException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   
}
